package com.mod;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.ip.IpParameters;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author jianxy
 * @date 2025-08-19 22:22
 */
@Configuration
public class ModbusConfig {
    @Value("${plc.ip:192.168.31.112}")
    private String plcIp;

    @Value("${plc.port:502}")
    private int plcPort;

    @Bean
    public ModbusFactory modbusFactory() {
        return new ModbusFactory();
    }

    @Bean
    public ModbusMaster modbusMaster() {
        IpParameters params = new IpParameters();
        params.setHost(plcIp);
        params.setPort(plcPort);
        ModbusMaster master = modbusFactory().createTcpMaster(params, true);
        master.setTimeout(5000); // 5秒超时
        master.setRetries(3);    // 重试3次
        try {
            master.init();
        } catch (ModbusInitException e) {
            throw new RuntimeException("Modbus 连接失败", e);
        }
        return master;
    }
}
